package com.hmall.service;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hdmall.business.common.common.ResponseCode;
import com.hdmall.business.common.common.ServerResponse;
import com.hdmall.business.common.common.ResponseCode;
import com.hdmall.business.common.common.ServerResponse;
import com.hmall.mapper.*;
import com.hmall.model.*;
import com.hmall.util.*;
import com.hmall.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class UserService {

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private SysUserDetailMapper sysUserDetailMapper;

    @Autowired
    private SysUserTempMapper sysUserTempMapper;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private SysUserDeptMapper sysUserDeptMapper;

    @Autowired
    MallPaymentVoucherMapper mallPaymentVoucherMapper;

    @Autowired
    JedisPool jedisPool;

    private final String DEFAULT_AVATOR = "http://huangyonghui.oss-cn-beijing.aliyuncs.com/imgupload/1528792148697.jpg?Expires=1844152147&OSSAccessKeyId=LTAIp8OhI23AvQo5&Signature=jpTukniaaNjBfejj1FGZutnoUJY%3D";

//查询买方名
    public ServerResponse<SysDeptVo> findBuyerDept(Integer userId){
        //买方用户id查询部门id
        SysDeptVo deptVo= null;
        try {
            deptVo = sysUserDeptMapper.selectDeptByUserId(userId);
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByStatus(ResponseCode.DEPT_SELECT_ISNULL_ERROR.getCode(),ResponseCode.DEPT_SELECT_ISNULL_ERROR.getDesc(),null) ;
        }
        if(null==deptVo){
            return ServerResponse.createByStatus(ResponseCode.DEPT_SELECT_ISNULL_ERROR.getCode(),ResponseCode.DEPT_SELECT_ISNULL_ERROR.getDesc(),null) ;
        }
        return ServerResponse.createBySuccess(deptVo);
    }

    public ServerResponse<Integer> selectDealerId(Integer userId){
        int dealerId= 0;
        try {
            dealerId = userMapper.selectByUserIdToDealerId(userId);
        } catch (Exception e) {
            e.printStackTrace();
            return  ServerResponse.createBySuccess(null);
        }

        return  ServerResponse.createBySuccess(dealerId);
    }




    //用以判断是否已经登录的User部分数据(拦截)
    public ServerResponse<SysUser> simpleUserByUsername(String username){
        SysUser user = userMapper.simpleUserByUsername(username);
      //  System.out.println("user" + user.toString());

        if(user != null){
            return ServerResponse.createBySuccess(user);
        }else{
            return ServerResponse.createByError();
        }
    }

    public String  selectByUserId(Integer userId){
        return  userMapper.selectByUserId(userId).getUsername();
    }
    public int  selectByUserIdToRoleId(Integer userId){
        return  userMapper.selectByUserIdToRoleId(userId);
    }
    public UserVo selectByRoleIdToUserName(Integer roleId){
        return  userMapper.selectByRoleIdToUserName(roleId);
    }

    public ServerResponse deleteVoucher(Integer userId, Integer voucherId) {

        MallPaymentVoucher mallPaymentVoucher = mallPaymentVoucherMapper.selectByUserIdAndVoucherId(userId, voucherId);
        if(null == mallPaymentVoucher){
            return ServerResponse.createByErrorMessage("该用户无该凭证信息");
        }

        if(mallPaymentVoucher.getIsAdopt() == 0){
            mallPaymentVoucherMapper.deleteByPrimaryKey(voucherId);
            return ServerResponse.createBySuccess();
        }else{
            return ServerResponse.createByErrorMessage("不是审核中的凭证无法删除");
        }

    }

/*

    //
    public ServerResponse<Map<String, String>> getUser(Integer userId) {

        int status;
        SysUserTemp sysUserTemp = sysUserTempMapper.selectByUserId(userId);
        if(sysUserTemp != null){
                status = sysUserTempMapper.queryStatus(userId);
            }else{
               status = 0;
            }
        Map<String, String> map = new HashMap<String, String>();
        map.put("status", String.valueOf(status));
        if(status == 3) map.put("message", "资质通过");
        else if(status == 0) map.put("message", "未提交审核");
        else if(status == 1) map.put("message", "审核中");
        else map.put("message", "审核取消");
        return ServerResponse.createBySuccess(map);

    }

    //公司模糊查询
    public ServerResponse<List<Map<String, Object>>> queryCompany(String subName) {

        List<Map<String, Object>> deptName = sysDeptMapper.queryName(subName);
        if(deptName.size() == 0){
            return ServerResponse.createByStatus(88, "找不到公司");
        }

        return ServerResponse.createBySuccess(deptName);

    }

    //完善用户信息
    public ServerResponse  prefectInformation(SysUserTempVo sysUserTempVo, Integer userId) {

        SysUserTemp sysUserTemp = new SysUserTemp();
        sysUserTemp.setUserId(userId);

        SysUserTemp oldUserTemp = sysUserTempMapper.selectByUserId(userId);
        //1. oldUserTemp == null
        //2. oldUserTemp != null 如果状态为 1 表示正在处理中不能提交资质 其他都可以
        //3. oldUserTemp != null 如果状态为 3  将temp表中的状态改为4 取消该资质
        // 删除detail表以及相关联的表
        if(oldUserTemp != null && oldUserTemp.getStatus() == 1) {
            return ServerResponse.createByStatus(16, "资质正在审核中，请勿重复提交");
        } else if(oldUserTemp != null && oldUserTemp.getStatus() == 3){
            //更新上传过的记录 temp表
            oldUserTemp.setStatus(4);


            //如果原先审核已经通过 修改用户的权限为普通用户
            sysUserRoleMapper.updateStatus(userId, 2);


            //修改
            int tempId = sysUserTempMapper.selectByUserId(userId).getTempId();
            sysUserTempMapper.updateStatus(tempId, 4);

            //删除detail表及其关联表保持资质唯一性
            //sysUserDetailMapper.
            sysUserDetailMapper.deleteByUserId(userId);
            sysUserDeptMapper.deleteByUserId(userId);
        }

        sysUserTemp.setAuthUrl(sysUserTempVo.getAuthUrl());
        sysUserTemp.setIdBackUrl(sysUserTempVo.getIdBackUrl());
        sysUserTemp.setIdFaceUrl(sysUserTempVo.getIdFaceUrl());
        sysUserTemp.setLicenseUrl(sysUserTempVo.getLicenseUrl());
        sysUserTemp.setLinkmanName(sysUserTempVo.getLinkmanName());
        sysUserTemp.setLinkmanTel(sysUserTempVo.getLinkmanTel());

        sysUserTemp.setTaxCertUrl(sysUserTempVo.getTaxCertUrl());
        //默认审核中
        sysUserTemp.setStatus(1);
        try {
            sysUserTempMapper.myInsert(sysUserTemp);
        }catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByStatus(16, "用户资料上传失败");
        }
        return ServerResponse.createBySuccess();
    }

    public ServerResponse update(SysUser user) {

        return ServerResponse.createBySuccess(userMapper.updateByPrimaryKey(user));
    }

    public ServerResponse getAptExamList(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<SysUserTemp> aptExamList = sysUserTempMapper.selectAll();
        PageInfo pageResult = new PageInfo(aptExamList);
        return ServerResponse.createBySuccess(pageResult);
    }

    public ServerResponse getUnExamList(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<SysUserTemp> aptExamList = sysUserTempMapper.selectUnExam();
        PageInfo pageResult = new PageInfo(aptExamList);
        return ServerResponse.createBySuccess(pageResult);
    }

    public ServerResponse getUnpassExamList(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<SysUserTemp> aptExamList = sysUserTempMapper.selectUnpassExam();
        PageInfo pageResult = new PageInfo(aptExamList);
        return ServerResponse.createBySuccess(pageResult);
    }

    public ServerResponse getPassExamList(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<SysUserTemp> aptExamList = sysUserTempMapper.selectPassExam();
        PageInfo pageResult = new PageInfo(aptExamList);
        return ServerResponse.createBySuccess(pageResult);
    }

   //营业执照
    public ServerResponse<List<ImgLicense>> licImgCastWord(String url) throws Exception {
        JSONObject res_obj = ImageRecog.imgLicense(url);

        ImgLicense imgLicense = new ImgLicense();
        imgLicense.setAddress((String) res_obj.get("address"));
        // imgLicense.setAngle((Float) res_obj.get("angle"));
        imgLicense.setBusiness((String) res_obj.get("business"));
        imgLicense.setCaptial((String) res_obj.get("captial"));
        // imgLicense.setElbem((String) res_obj.get("elbem"));
        imgLicense.setName((String) res_obj.get("name"));
        imgLicense.setPerson((String) res_obj.get("person"));

        String establishDate = (String) res_obj.get("establish_date");
        String strEstablishDate = establishDate.substring(0, 4) + "/" + establishDate.substring(4, 6) + "/" + establishDate.substring(6, 7);
        imgLicense.setEstablishDate(strEstablishDate);
        String validPeriod = (String) res_obj.get("valid_period");
        String strValidPeriod = validPeriod.substring(0, 4) + "/" + validPeriod.substring(4, 6) + "/" + validPeriod.substring(6, 7);
        imgLicense.setValidPeriod(strValidPeriod);

        imgLicense.setRegNum((String) res_obj.get("reg_num"));
        //  imgLicense.setStamp((String) res_obj.get("stamp"));
        //  imgLicense.setQrcode((String) res_obj.get("qrcode"));
        imgLicense.setRequestId((String) res_obj.get("request_id"));

        Boolean flag = true;
        imgLicense.setSuccess((res_obj.get("success") == flag) ? "true" : "false");

       // imgLicenseMapper.insert(imgLicense);
        List<ImgLicense> imgLicenseList = new ArrayList<ImgLicense>();
        imgLicenseList.add(imgLicense);
        return ServerResponse.createBySuccess(imgLicenseList);
    }

    public ServerResponse<ImgLegalId> idImgCastWord(String url, String config) throws Exception {

        JSONObject res_obj = ImageRecog.imgLegalId(url, config);

        ImgLegalId imgLegalId = new ImgLegalId();
        imgLegalId.setNationality((String) res_obj.get("nationality"));
        imgLegalId.setName((String) res_obj.get("name"));
        imgLegalId.setAddress((String) res_obj.get("address"));
        imgLegalId.setNum((String) res_obj.get("num"));

        return ServerResponse.createBySuccess(imgLegalId);
    }

   //查询发票
    public ServerResponse<UnitContactVo> selectInvoiceByUser(Integer userId){
        UnitContactVo unitContactVo=null;
        try {
            unitContactVo= sysUserDetailMapper.selectUnitByUserId(userId);
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByStatus(ResponseCode.INVOICE_NOT_FOUND.getCode(), ResponseCode.INVOICE_NOT_FOUND.getDesc(),null);
        }
        if(null==unitContactVo){
            return ServerResponse.createByStatus(ResponseCode.INVOICE_NOT_FOUND.getCode(), ResponseCode.INVOICE_NOT_FOUND.getDesc(),null);

        }
        return  ServerResponse.createBySuccess(unitContactVo);

    }

    public ServerResponse<SysUserDetailVo> getPerfectInformation(Integer userId) {

        //资质信息
        SysUserDetailVo userDetailVo = sysUserDetailMapper.selectByUserIdVo(userId);
        if(userDetailVo == null) return ServerResponse.createByStatus(17, "还未通过资质审核，无法查看资质信息");

        return ServerResponse.createBySuccess(userDetailVo);
    }

    //获取审核信息
    public ServerResponse<SysUserTemp> getTempPrefectInformation(Integer userId) {

        SysUserTemp userTemp =  sysUserTempMapper.selectByUserId(userId);

        return ServerResponse.createBySuccess(userTemp);
    }*/



}
